package controllers.service;

import java.net.MalformedURLException;
import java.net.URL;

import javax.persistence.EntityManager;

import ws.gr.aueb.ebill.payment.EBillPayment;
import ws.gr.aueb.ebill.payment.EBillPaymentFault_Exception;
import ws.gr.aueb.ebill.payment.EBillPaymentPortType;
import ws.gr.aueb.ebill.payment.EBillPaymentRequest;
import ws.gr.aueb.ebill.payment.EBillPaymentResponse;
import models.domain.Payment;
import models.persistence.JPAUtil;

public class PaymentService {

	/**
	 * Returns true in case of successful payment
	 * 
	 * @param payment
	 * @param creditCardNumber
	 * @param cardName
	 * @param expDate
	 * @param cvs
	 * @return
	 */
	public boolean initializePayment(Payment payment, String amount) {

		if (validatePaymentData(payment,amount) == true) {
			addToPayment(payment);
			return true;
		}

		return false;
	}

	/**
	 * Return true on correct validation false on error
	 * 
	 * @param payment
	 * @param creditCardNumber
	 * @param cardName
	 * @param expDate
	 * @param cvs
	 * @return
	 */
	public boolean validatePaymentData(Payment payment, String amount) {
		
		try {
			EBillPayment paymentService=new EBillPayment(new URL("http://192.168.2.6:8088/mockeBillPaymentBinding?wsdl"));
			try {
				EBillPaymentRequest req=new EBillPaymentRequest();
				
				
				req.setFirstName(payment.getCreditCardName());
				req.setCreditCardNumber(payment.getCreditCardNo());
				req.setAmount(String.valueOf(amount));
				
				
				EBillPaymentResponse respo=paymentService.getEBillPaymentPort().eBillPayment(req);
				
				if(respo.getStatus()=="OK"){
					return true;
				}else{
					return false;
				}
				
			} catch (EBillPaymentFault_Exception e) {
				return false;
				
			}
		} catch (MalformedURLException e) {
			return false;
			
		}
		
		
	}
	
	

	

	/**
	 * Add a payment
	 * 
	 * @param payment
	 */
	public void addToPayment(Payment payment) {

		EntityManager em = JPAUtil.getCurrentEntityManager();
		em.persist(payment);

	}

}
